<template>
  <div class="ace-editor-container" :style="containerStyle">
    <div ref="editor" class="ace-editor"></div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import ace from 'ace-builds/src-noconflict/ace'
import 'ace-builds/src-noconflict/theme-monokai'
import 'ace-builds/src-noconflict/mode-python'
import 'ace-builds/src-noconflict/mode-sh'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/ext-language_tools'

// 导入更多主题
import 'ace-builds/src-noconflict/theme-github'
import 'ace-builds/src-noconflict/theme-tomorrow'
import 'ace-builds/src-noconflict/theme-kuroir'
import 'ace-builds/src-noconflict/theme-twilight'
import 'ace-builds/src-noconflict/theme-xcode'
import 'ace-builds/src-noconflict/theme-textmate'
import 'ace-builds/src-noconflict/theme-solarized_dark'
import 'ace-builds/src-noconflict/theme-solarized_light'
import 'ace-builds/src-noconflict/theme-terminal'

export default {
  name: 'AceEditor',
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    language: {
      type: String,
      default: 'python'
    },
    theme: {
      type: String,
      default: 'monokai'
    },
    fontSize: {
      type: Number,
      default: 14
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    showGutter: {
      type: Boolean,
      default: true
    },
    showPrintMargin: {
      type: Boolean,
      default: true
    },
    highlightActiveLine: {
      type: Boolean,
      default: true
    },
    enableBasicAutocompletion: {
      type: Boolean,
      default: true
    },
    enableLiveAutocompletion: {
      type: Boolean,
      default: true
    },
    enableSnippets: {
      type: Boolean,
      default: true
    },
    height: {
      type: String,
      default: '400px'
    },
    width: {
      type: String,
      default: '100%'
    },
    // 新增：是否自动调整宽度以匹配输入框
    autoWidth: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'change', 'init'],
  setup(props, { emit }) {
    const editor = ref(null)
    const editorInstance = ref(null)
    const isSettingValue = ref(false)

    const containerStyle = ref({
      height: props.height,
      width: props.autoWidth ? '100%' : props.width
    })

    const languageMap = {
      python: 'python',
      shell: 'sh',
      javascript: 'javascript'
    }

    const initEditor = () => {
      if (!editor.value) return

      // 初始化编辑器
      editorInstance.value = ace.edit(editor.value)
      
      // 设置主题
      editorInstance.value.setTheme(`ace/theme/${props.theme}`)
      
      // 设置语言模式
      const mode = languageMap[props.language] || 'text'
      editorInstance.value.session.setMode(`ace/mode/${mode}`)
      
      // 基本配置
      editorInstance.value.setOptions({
        fontSize: `${props.fontSize}px`,
        showGutter: props.showGutter,
        showPrintMargin: props.showPrintMargin,
        highlightActiveLine: props.highlightActiveLine,
        enableBasicAutocompletion: props.enableBasicAutocompletion,
        enableLiveAutocompletion: props.enableLiveAutocompletion,
        enableSnippets: props.enableSnippets,
        readOnly: props.readOnly,
        wrap: true,
        autoScrollEditorIntoView: true,
        copyWithEmptySelection: true,
        useWorker: false // 禁用 worker 以提高性能
      })

      // 设置初始值
      editorInstance.value.setValue(props.modelValue, -1)
      
      // 监听内容变化
      editorInstance.value.on('change', () => {
        if (!isSettingValue.value) {
          const value = editorInstance.value.getValue()
          emit('update:modelValue', value)
          emit('change', value)
        }
      })

      // 调整编辑器大小以适应容器
      nextTick(() => {
        if (editorInstance.value) {
          editorInstance.value.resize()
        }
      })

      // 触发初始化完成事件
      emit('init', editorInstance.value)
    }

    // 监听语言变化
    watch(() => props.language, (newLanguage) => {
      if (editorInstance.value) {
        const mode = languageMap[newLanguage] || 'text'
        editorInstance.value.session.setMode(`ace/mode/${mode}`)
      }
    })

    // 监听主题变化
    watch(() => props.theme, (newTheme) => {
      if (editorInstance.value) {
        editorInstance.value.setTheme(`ace/theme/${newTheme}`)
      }
    })

    // 监听字体大小变化
    watch(() => props.fontSize, (newFontSize) => {
      if (editorInstance.value) {
        editorInstance.value.setOptions({
          fontSize: `${newFontSize}px`
        })
      }
    })

    // 监听只读状态变化
    watch(() => props.readOnly, (newReadOnly) => {
      if (editorInstance.value) {
        editorInstance.value.setReadOnly(newReadOnly)
      }
    })

    // 监听模型值变化
    watch(() => props.modelValue, (newValue) => {
      if (editorInstance.value && editorInstance.value.getValue() !== newValue) {
        isSettingValue.value = true
        const cursorPosition = editorInstance.value.getCursorPosition()
        editorInstance.value.setValue(newValue, -1)
        editorInstance.value.moveCursorToPosition(cursorPosition)
        isSettingValue.value = false
      }
    })

    // 监听宽度变化
    watch(() => props.width, () => {
      nextTick(() => {
        if (editorInstance.value) {
          editorInstance.value.resize()
        }
      })
    })

    onMounted(() => {
      nextTick(() => {
        initEditor()
      })
    })

    onUnmounted(() => {
      if (editorInstance.value) {
        editorInstance.value.destroy()
      }
    })

    // 暴露编辑器实例的方法
    const focus = () => {
      if (editorInstance.value) {
        editorInstance.value.focus()
      }
    }

    const getValue = () => {
      return editorInstance.value ? editorInstance.value.getValue() : ''
    }

    const setValue = (value) => {
      if (editorInstance.value) {
        isSettingValue.value = true
        editorInstance.value.setValue(value, -1)
        isSettingValue.value = false
      }
    }

    const resize = () => {
      if (editorInstance.value) {
        editorInstance.value.resize()
      }
    }

    return {
      editor,
      editorInstance,
      containerStyle,
      focus,
      getValue,
      setValue,
      resize
    }
  }
}
</script>

<style scoped>
.ace-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  width: 100%; /* 确保容器宽度为100% */
}

.ace-editor {
  height: 100%;
  width: 100%;
}
</style>
